import KeepAlive from 'react-activation'
import { Route, Routes, Navigate } from 'react-router-dom'

import MenuPage from '@/page/Menu/index'
import LoginPage from '@/page/Login/index'
import UserPage from '@/page/User/index'
import RolesPage from '@/page/Roles/index'
import RightsPage from '@/page/Rights/index'
import GoodsPage from '@/page/Goods/index'
import AddGoodsPage from '@/page/Goods/components/AddGoods/index'
import CategoryPage from '@/page/Category/index'
import ParamsPage from '@/page/Params/index'
import ReportsPage from '@/page/Report/index'

const Router = () => {
  const routes = [
    {path: '/', element: <MenuPage/>, children: [
      {path: '/users', auth: true, element: <UserPage/>, keepAlive: true},
      {path: '/roles', auth: true, element: <RolesPage/>, keepAlive: true},
      {path: '/rights', auth: true, element: <RightsPage/>, keepAlive: true},
      {path: '/goods', auth: true, element: <GoodsPage/>, keepAlive: true},
      {path: '/addGoods', auth: true, element: <AddGoodsPage/>, keepAlive: true},
      {path: '/categories', auth: true, element: <CategoryPage/>, keepAlive: true},
      {path: '/params', auth: true, element: <ParamsPage/>, keepAlive: true},
      {path: '/reports', auth: true, element: <ReportsPage/> , keepAlive: true},
      {path: '/', element: <Navigate to='/users'/>}
    ]},
    {path: '/login', element: <LoginPage/>}
  ]
  
  const hasKeepAlive = (item: {path: string, element: any}) => {
    return <KeepAlive when={[true, true,]} saveScrollPosition={'screen'} key={item.path}>{item.element}</KeepAlive>
  }

  const show = (item: any) => {
    // if(item.path === pathname && item.auth && (getCookie('token') === undefined || getCookie('token') === null)) { // 需要验证 且未登录的
      // message.success('请先登录', 0.1, () => { navigater('/login') })
    // } else {
      if(item.keepAlive) { // 需要缓存
        console.log(1)
        return (
          <Route path={item.path} key={item.path} element={hasKeepAlive(item)}>{item.children && RouteNav(item.children)}</Route>
        )
      } else { // 不需要缓存
        console.log(2)
        return (
          <Route path={item.path} key={item.path} element={item.element}>{item.children && RouteNav(item.children)}</Route>  
        )  
      }
    // }
  }

  const RouteNav = (params: any) => {
    return params.map((item: any) => {
      return show(item)
    })
  }

  return (
    <Routes>{RouteNav(routes)}</Routes>
  )
}
export default Router